<template>
	<view>
		<free-nav-bar showBack :backIconType="false">
			<view slot="right">
				<text @click="changeCodeLogin = !changeCodeLogin">{{ changeCodeLogin ? '验证码登录' : '账号登录' }}</text>
			</view>
		</free-nav-bar>

		<!-- 验证码登录注册 -->
		<view class="main mt-6">
			<view class="font-lg font-weight text-primary">{{ changeCodeLogin ? '账号密码登录' : '验证码登录' }}</view>
			<!-- 手机号 -->
			<view class="flex align-center border-bottom mt-8" style="height:80rpx ;">
				<!-- 电话选区 -->
				<view class="region-title">+{{ region }}</view>
				<!-- <view class="ml-1 iconfont icon-iconicyihuifu-13"></view> -->
				<view class="font-lg">
					<input type="number" v-model="phone" placeholder="请输入手机号" placeholder-class="placeholder"
						maxlength="11" />
				</view>
				<text v-if="phone" class="icon-a-qingkongpng iconfont ml-auto text-light" @click="phone = ''"></text>
			</view>

			<!-- 密码登录 -->
			<view class="flex align-center  border-bottom mt-5" style="height:80rpx ;" v-if="changeCodeLogin">
				<view class="text-secondary password-title">密码</view>
				<view class="flex align-center w-100">
					<input type="password" style="width: 90%;" v-if="isShowPassowrd" v-model="password"
						placeholder="请输入密码" placeholder-class="placeholder" maxlength="16" />
					<input type="text" v-else v-model="password" placeholder="请输入密码" placeholder-class="placeholder"
						maxlength="16" />
					<view v-if="password" class="clickArea mr-1  icon-a-qingkongpng iconfont text-light"
						@click="password = ''"></view>
				</view>
				<view class="clickArea ml-auto" @click="isShowPassowrd = !isShowPassowrd">
					<view class="iconfont text-secondary"
						:class="isShowPassowrd ? 'icon-a-passwordon' : 'icon-a-passwordoff'"></view>
				</view>
			</view>

			<!-- 验证码登录 -->
			<view class="flex align-center justify-between mt-5" style="height:80rpx ;" v-else>
				<view class="font-sm border-bottom  flex align-center" style="width: 355rpx;height: 80rpx;"
					@click="clickCode">
					<input type="number" v-model="code" placeholder="请输入验证码" placeholder-class="placeholder"
						:disabled="sendCode ? false : true" maxlength="4" />
					<view v-if="code" class="icon-a-qingkongpng iconfont text-light" @click="code = ''"></view>
				</view>
				<view class="text-light text-white px-2 py-1" :style="isActiveCode" @click="send()">{{ codeText }}
				</view>
			</view>

			<!-- 登录 -->
			<view class="text-white mt-9 flex align-center justify-center" :style="isActiveLogin"
				style="height: 90rpx;box-shadow: 0rpx -6rpx 8rpx 0rpx rgba(0, 0, 0, 0.03);" @click="login()">登录
			</view>

			<view class="text-primary mt-3 flex justify-between">
				<view @click="goRegister()">账号注册</view>
				<view @click="forgetPassword()">忘记密码</view>
			</view>

			<!-- 滑块验证 -->
			<view>
				<uni-popup ref="popup" type="center">
					<view class="sunui">
						<view class="font-sm close p-2" @click="close()">关闭</view>
						<sunui-mverify @change="mverify"></sunui-mverify>
					</view>
				</uni-popup>
			</view>
			<!-- 协议 -->
			<view class="font-sm flex align-center justify-center agree" style="margin-top: 457rpx;">
				<checkbox-group name="" @change="checkboxChange">
					<label>
						<checkbox value="0" color="#3C8EFF" style="transform:scale(0.5);color:#3C8EFF;" />
					</label>
				</checkbox-group>
				<text class="text-secondary bottomStyle">同意</text>
				<text class="main-text-color bottomStyle" @click="nurseNeed()">《护士小鹿服务协议》</text>
				<text class="text-secondary bottomStyle">和</text>
				<text class="main-text-color bottomStyle" @click="hide()">《隐私政策》</text>
			</view>

		</view>
		<uni-popup ref="message" type="center">
			<view class="permission-bc" style="width: 540rpx;height:676rpx">
				<view style="height: 73%;"></view>
				<view @click="getService" class="d-center" style="height: 78rpx;color: #fff;font-size: 32rpx;">马上开启
				</view>
				<view @click="closeMessage" class="d-center" style="height: 78rpx;font-size: 28rpx;color: #999999;">以后再说
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import permision from '@/common/js/permission.js'
	import {
		getLastestLocation
	} from '@/common/js/location.js'
	// 自定义导航栏
	import freeNavBar from '@/components/common/nav-bar/free-nav-bar.vue'

	// 引入弹窗组件
	import uniPopup from '@/components/uni-ui/uni-popup/uni-popup.vue'
	// 弹窗验证
	import sunuiMverify from '@/components/uni-ui/sunui-mverify/sunui-mverify.vue'
	// 验证密码手机号
	import {
		validatePassword,
		validatePhone,
		validateCode,
		clearSpace,
	} from '@/common/js/validate.js'
	import {
		loginByPassword,
		loginByVerificationCode,
		senMsg,
		getLoginInfo,
	} from '../../../apis/login/index.js'
	export default {
		components: {
			freeNavBar,
			uniPopup,
			sunuiMverify,
		},
		data() {
			return {
				loc: -1,
				uuid: '',
				phone: '', //手机号码
				code: '', //验证码
				password: '', //密码
				codeText: '发送验证码', //验证码按钮显示内容
				sendCode: false, //是否点击了发送验证码
				changeCodeLogin: true, //默认是账号登录
				isShowPassowrd: true, //是否显示密码
				countTimer: 60, //计时器
				region: 86, //中国电话区域
				resultData: {}, //滑块验证数据
				isAgree: false,
				type: '', //判断退出登录 及 401时的登录操作
				iosNum: 0, //判断ios退出
			}
		},
		onShow() {
			let _this = this
			this.getMision()

		},
		onLoad(option) {
			this.getMision()
			getLastestLocation()
			console.log(option, '登录返回判断')
			if (option.type) {
				this.type = option.type
			}
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('isLogin')
			uni.removeStorageSync('token')
		},
		// #ifdef APP-PLUS
		onBackPress() {
			if (this.type == 1) {
				if (uni.getSystemInfoSync().platform === 'ios') {
					console.log(uni.getSystemInfoSync().platform, '返回')
					this.iosNum++
					if (this.iosNum == 2) {
						plus.ios
							.import('UIApplication')
							.sharedApplication()
							.performSelector('exit')
					}
				}
				return
			}
		},
		// #endif
		computed: {
			// 动态改变背景颜色
			isActiveCode() {
				return this.phone ?
					`background-color: #3C8EFF;` :
					`background: #ADCEFB`
			},
			isActiveLogin() {
				if ((this.code && this.phone) || (this.password && this.phone)) {
					return `background-color: #3C8EFF;`
				} else {
					return `background: #ADCEFB`
				}
			},
		},

		methods: {
			async getMision() {
				if (uni.getSystemInfoSync().platform == 'android') {
					// 安卓权限查询
					this.loc = await permision.checkAndroidSelfPermission(
						'android.permission.READ_PHONE_STATE'
					)
					console.log('anzhuo', this.loc)
					if (this.loc == -1) {
						this.$refs.message.open()
					} else {
						this.getService()
					}
				}
			},
			getService() {
				this.closeMessage()
				// 3. 手机设备唯一标识号
				// #ifdef APP-PLUS
				plus.device.getInfo({
					success(res) {
						let uuid = res.uuid
						_this.uuid = res.uuid
						// console.log(_this.uuid,'uuid--login');
						_this.$store.commit('setUuid', uuid)
					},
				})
				// #endif
			},
			async goLogin() {
				await univerifyLogin(
					(status) => {
						// 0 关闭，1 选择其它登录方式
						console.log(status, '登陆失败了----')
						if (status == 0) {
							uni.navigateBack({
								delta: 1,
							})
						} else if (status == 1) {
							// 选择了其它登录方式
						}
						// 是否一键登录判断，还是store中直接写？
						// this.$store.dispatch('goLogin')
					},
					(res) => {
						console.log('个人中心一键登录：', res)
						// 存储用户xinxi
						this.$store.dispatch('userOneKeyLogin', res)
					}
				)
			},
			nurseNeed() {
				uni.navigateTo({
					url: '../../mine/nurse-need/nurse-need',
				})
			},
			hide() {
				uni.navigateTo({
					url: '../../mine/hide/hide',
				})
			},
			// 是否同意
			checkboxChange(e) {
				let flag = e.target.value.indexOf('0')
				if (flag != -1) {
					this.isAgree = true
				} else {
					this.isAgree = false
				}
			},
			// 定时器倒计时
			countDownTime() {
				if (this.countTimer == 60) {
					this.codeText = '重新发送' + this.countTimer + 's'
					var timer = setInterval(() => {
						if (this.countTimer > 0) {
							this.countTimer--
							this.codeText = '重新发送' + this.countTimer + 's'
						} else {
							this.codeText = '发送验证码'
							clearInterval(timer)
							this.countTimer = 60
						}
					}, 1000)
				}
			},

			// 发送验证码
			send() {
				// 校验手机号
				if (validatePhone(this.phone, this.region)) {
					// 打开验证弹窗
					this.$refs.popup.open()
				}
			},
			clickCode() {
				if (!this.sendCode) {
					plus.nativeUI.toast('请点击右侧发送验证码~')
					// uni.showToast({
					// 	title: '请点击右侧发送验证码~',
					// 	icon: 'none'
					// });
				}
			},
			// 滑块验证
			mverify(e) {
				console.log('验证结果:', e)
				// 验证通过
				if (e.msg) {
					setTimeout(() => {
						this.close()
					}, 500)
					// 发送验证码
					senMsg({
						mobile: this.phone,
						uuid: this.$store.state.uuid,
						type: 5,
					}).then((res) => {
						if (res.success) {
							plus.nativeUI.toast(res.codeMsg.msg)
							// uni.showToast({
							// 	title: res.codeMsg.msg,
							// 	icon: 'none'
							// });
							// 计时器
							this.countDownTime()
						}
					})
					// 用户可以输入验证码了
					this.sendCode = true
				}
			},
			// 关闭弹窗
			close() {
				this.$refs.popup.close()
			},
			// 用户注册界面
			goRegister() {
				uni.navigateTo({
					url: '../register/register',
				})
			},
			closeMessage() {
				this.$refs.message.close()
			},
			async login() {
				// return console.log("cid=====",this.$store.state.cid)
				if (!this.isAgree) {
					// #ifdef APP-PLUS
					plus.nativeUI.toast('请您同意产品服务协议及隐私政策')
					// #endif
					// uni.showToast({
					// 	title: '请您同意产品服务协议及隐私政策',
					// 	icon: 'none'
					// });
					return
				}
				if (this.changeCodeLogin) {
					// 验证手机号、密码
					if (
						validatePhone(this.phone, this.region) &&
						validatePassword(this.password)
					) {
						let data = {
							account: clearSpace(this.phone),
							agreement: 1,
							password: clearSpace(this.password),
							phoneType: this.region,
							registerSource: this.$store.state.system.brand,
							uuid: uni.getStorageSync('uuid'),
							cid: this.$store.state.cid,
						}
						uni.showLoading()
						console.log('密码是数据', data)

						loginByPassword(data).then((res) => {
							console.log('res======', res)
							if (res.success) {
								let payload = {
									id: res.object.nurseId,
									token: res.object.token,
								}
								// this.$store.commit('setUserInfo',payload)
								this.$store.dispatch('getUserInfo', payload)
								// #ifdef APP-PLUS
								plus.nativeUI.toast('登录成功~')
								// #endif
								// uni.showToast({
								// 	title:'登录成功~',
								// 	icon:'none',
								// })
								uni.setStorageSync('isLogin', true)
								// setTimeout(()=>{
								// 	uni.switchTab({
								// 		url:'../../tabbars/index/index?login=true'
								// 	})
								// },300)
								this.$store.commit('setToken', res.object.token)
							}
						}).finally(() => {
							uni.hideLoading()
						})

					}
				} else {
					this.loginByCode()
				}
			},
			// 验证码登录
			loginByCode() {
				if (
					validatePhone(this.phone, this.region) &&
					validateCode(this.code)
				) {
					let data = {
						code: clearSpace(this.code),
						agreement: 1,
						mobile: clearSpace(this.phone),
						phoneType: this.region,
						registerSource: this.$store.state.system.brand,
						uuid: uni.getStorageSync('uuid'),
						cid: this.$store.state.cid,
					}
					console.log(data, 'mmmmmmmmmmmmmmmmmmm')
					uni.showLoading()
					loginByVerificationCode(data).then(res => {
						if (res.success) {
							this.$store.commit('setToken', res.object.token)
							let payload = {
								id: res.object.nurseId,
								token: res.object.token,
							}
							uni.removeStorageSync('userInfo')
							uni.removeStorageSync('isLogin')
							this.$store.dispatch('getUserInfo', payload)
							// #ifdef APP-PLUS
							plus.nativeUI.toast('登录成功~')
							// #endif
							// #ifdef H5
							uni.showToast({
								title: '登录成功~',
								icon: 'none',
							})
							// #endif
							uni.setStorageSync('isLogin', true) //赋值
							// setTimeout(()=>{
							// 	uni.switchTab({
							// 		url:'../../tabbars/index/index'
							// 	})
							// },300)
						}
					}).finally(() => {
						uni.hideLoading()
					})


				}
			},
			// 忘记密码
			forgetPassword() {
				uni.navigateTo({
					url: '../forget-password/forget-password',
				})
			},
		},
	}
</script>

<style lang="less" scoped>
	// 输入框输入的时候字体为32rpx
	/deep/.uni-input-input {
		/*deep样式穿透，直接从底部修改*/
		font-size: 32rpx !important;
	}

	.main {
		padding: 0 80rpx 0 78rpx;
	}

	.icon-a-qingkongpng {
		font-size: 48rpx;
	}

	// 遮罩层样式
	.mask {
		width: 100%;
		height: 100vh;
		position: fixed;
		top: -88rpx;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999999;
	}

	// 滑块验证样式
	.sunui {
		position: relative;
		width: 652rpx;
		height: 320rpx;
		background-color: #ffffff;
		margin: 0 auto;
	}

	.close {
		width: 90rpx;
		height: 90rpx;
	}

	.password-title {
		width: 150rpx;
		margin-right: 32rpx;
	}

	.region-title {
		width: 88rpx;
		margin-right: 32rpx;
		color: #3d3d3d;
	}

	.permission-bc {
		background-image: url('http://loto.oss-cn-shanghai.aliyuncs.com/email/8125ac62f7ad4ad2.png');
		background-size: 100%;
		background-repeat: no-repeat;
	}
</style>